<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<script type="text/javascript" src="${pageContext.request.contextPath}/lib/geoxml3.js"></script>
<script type="text/javascript"
        src="http://maps.googleapis.com/maps/api/js?v=3.6&sensor=false&libraries=geometry">
</script>
<script type="text/javascript">
var map;
// Create a meausure object to store our markers, MVCArrays, lines and polygons
var measure = {
    mvcLine: new google.maps.MVCArray(),
    mvcPolygon: new google.maps.MVCArray(),
    mvcMarkers: new google.maps.MVCArray(),
    line: null,
    polygon: null
};

$(document).ready(function () {
    $('#kmlFile').hide();
    $('#map').hide();
    displayKmlFromDB();
});

//calculate Area
function displayKmlFromDB() {
    var kmlString = '<s:property value="land.kmlString"/>';
    if (kmlString != null && kmlString.length != 0) {
        var kmlReferenceNumber = '<s:property value="land.referenceNumber"/>';
        var middlePoint = '<s:property value="land.kmlMiddlePoint"/>';

        $('#kmlFile').show();
        $('#map').show();
        var melbourne = new google.maps.LatLng(-122.0822035425683, 37.42228990140251);
        var mapOptions = {
            zoom:      12,
            center:    melbourne,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            draggableCursor: "crosshair"
        };
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        var geoXml = new geoXML3.parser({map: map, singleInfoWindow: true});

        var kml = "<kml><Placemark><name>Land</name><Polygon><extrude>1</extrude><altitudeMode>relativeToGround</altitudeMode><outerBoundaryIs><LinearRing><coordinates>" + kmlString + " </coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark><Placemark><name>" + kmlReferenceNumber + "</name><description>Middle of the Land</description><Point><coordinates>" + middlePoint + "</coordinates><referenceNo>" + kmlReferenceNumber + "</referenceNo></Point></Placemark></kml>";
        geoXml.parseKmlString(kml);
        google.maps.event.addListener(map, "click", function(evt) {
            // When the map is clicked, pass the LatLng obect to the measureAdd function
            measureAdd(evt.latLng);
        });
        var landArea = '<s:property value="land.kmlLandArea"/>';
        if (landArea == null || landArea == 0) {
            calculateAreaFromDB(<s:property value="land.id"/>);
        } else {
            changeHectareKml();
        }
        measureReset();

        //do if coordinates not empty
      /*  $.getJSON('${pageContext.request.contextPath}/common/GPSImageService', {id:landId,type:"GPSImage"}, function(data) {
            var lat;
            var lon;
            //todo: remove this loop
            if(data.GPSList.length == 0)  {
                $('#messageBox').html("Warning : " +data.msg);
            } else {

                for (var i = 0; i < data.GPSList.length; i++) {
                    lat = data.GPSList[i].latitude;
                    lon = data.GPSList[i].longitude;
                }

                var coordinate = new google.maps.LatLng(lat,lon);
                var isWithinPolygon = 0;

                for (var i=0; i<geoXml.docs[0].gpolygons.length; i++) {
                    if (google.maps.geometry.poly.containsLocation(coordinate,geoXml.docs[0].gpolygons[i])) {
                        isWithinPolygon = 1;
                        break;
                    }
                }

                if(isWithinPolygon==0){
                    $('#messageBox').html("Warning : The attached land image is not an image of this land");
                }
            }
        });*/
    }
}

function hideKmlMap() {
    $('#map').hide();
    measureReset();
}

function measureAdd(latLng) {
    // Add a draggable marker to the map where the user clicked
    var marker = new google.maps.Marker({
        map: map,
        position: latLng,
        draggable: true,
        raiseOnDrag: false,
        title: "Drag me to change shape",
        icon: new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5))
    });

    // Add this LatLng to our line and polygon MVCArrays
    // Objects added to these MVCArrays automatically update the line and polygon shapes on the map
    measure.mvcLine.push(latLng);
    measure.mvcPolygon.push(latLng);

    // Push this marker to an MVCArray
    // This way later we can loop through the array and remove them when measuring is done
    measure.mvcMarkers.push(marker);

    // Get the index position of the LatLng we just pushed into the MVCArray
    // We'll need this later to update the MVCArray if the user moves the measure vertexes
    var latLngIndex = measure.mvcLine.getLength() - 1;

    // When the user mouses over the measure vertex markers, change shape and color to make it obvious they can be moved
    google.maps.event.addListener(marker, "mouseover", function() {
        marker.setIcon(new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(15, 15), new google.maps.Point(0, 0), new google.maps.Point(8, 8)));
    });

    // Change back to the default marker when the user mouses out
    google.maps.event.addListener(marker, "mouseout", function() {
        marker.setIcon(new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5)));
    });

    // When the measure vertex markers are dragged, update the geometry of the line and polygon by resetting the
    //     LatLng at this position
    google.maps.event.addListener(marker, "drag", function(evt) {
        measure.mvcLine.setAt(latLngIndex, evt.latLng);
        measure.mvcPolygon.setAt(latLngIndex, evt.latLng);
    });

    // When dragging has ended and there is more than one vertex, measure length, area.
    google.maps.event.addListener(marker, "dragend", function() {
        if (measure.mvcLine.getLength() > 1) {
            measureCalc();
        }
    });

    // If there is more than one vertex on the line
    if (measure.mvcLine.getLength() > 1) {

        // If the line hasn't been created yet
        if (!measure.line) {

            // Create the line (google.maps.Polyline)
            measure.line = new google.maps.Polyline({
                map: map,
                clickable: false,
                strokeColor: "#FF0000",
                strokeOpacity: 1,
                strokeWeight: 3,
                path:measure.mvcLine
            });

        }

        // If there is more than two vertexes for a polygon
        if (measure.mvcPolygon.getLength() > 2) {

            // If the polygon hasn't been created yet
            if (!measure.polygon) {

                // Create the polygon (google.maps.Polygon)
                measure.polygon = new google.maps.Polygon({
                    clickable: false,
                    map: map,
                    fillOpacity: 0.25,
                    strokeOpacity: 0,
                    paths: measure.mvcPolygon
                });

            }

        }

    }

    // If there's more than one vertex, measure length, area.
    if (measure.mvcLine.getLength() > 1) {
        measureCalc();
    }

}

function measureCalc() {

    // Use the Google Maps geometry library to measure the length of the line
    var length = google.maps.geometry.spherical.computeLength(measure.line.getPath());
    jQuery("#span-length").text(length.toFixed(1))

    // If we have a polygon (>2 vertexes in the mvcPolygon MVCArray)
    if (measure.mvcPolygon.getLength() > 2) {
        // Use the Google Maps geometry library to measure the area of the polygon
        var area = google.maps.geometry.spherical.computeArea(measure.polygon.getPath());
        jQuery("#span-area").text(area.toFixed(1));
    }

}

function measureReset() {

    // If we have a polygon or a line, remove them from the map and set null
    if (measure.polygon) {
        measure.polygon.setMap(null);
        measure.polygon = null;
    }
    if (measure.line) {
        measure.line.setMap(null);
        measure.line = null
    }

    // Empty the mvcLine and mvcPolygon MVCArrays
    measure.mvcLine.clear();
    measure.mvcPolygon.clear();

    // Loop through the markers MVCArray and remove each from the map, then empty it
    measure.mvcMarkers.forEach(function(elem, index) {
        elem.setMap(null);
    });
    measure.mvcMarkers.clear();

    jQuery("#span-length,#span-area").text(0);

}
//calculate Area
function calculateAreaFromDB(landId) {

    var area;
    var type = "kmlString";
    $.getJSON('${pageContext.request.contextPath}/common/LandLookupService', {type:type,id:landId}, function(data) {
        if (data != null && data.latLanVal != null) {
            var AList = data.latLanVal;
            var points = new Array();
            var Alenth = AList.length;
            var j = 0;
            for (i = 0; i < Alenth; i++) {
                //points[j] = new google.maps.LatLng(AList[i++], AList[i]);
                points[j++] = new google.maps.LatLng(AList[i + 1], AList[i]);
                i++;
                measureAdd(points[j - 1]);
            }

            area = google.maps.geometry.spherical.computeArea(points);
            // alert("b="+area);
            $('#kmlArea').val(area);
            changeHectareKml();
        }
    });
    return area;
}


</script>

<tr id="kmlFile">
    <td colspan="4">
<tr>
    <td>
        <input value="View Map" type="button" onclick="displayKmlFromDB();">
        <input value="Hide Map" type="button" onclick="hideKmlMap();">
    </td>
</tr>
<table>

    <tr><p><s:label value="%{getText('length.label')}"/> : <span id="span-length">0</span> m <br>
        <s:label
                value="%{getText('area_grey_area.label')}"/>: <span
                id="span-area">0</span> m² - <a href="javascript:measureReset();"><s:label
                value="%{getText('reset_measure.label')}"/></a></p></tr>

    <tr>
        <td>
            <div id="map">
                <%--<s:label value="Land Map"/>--%>
                <div id='map_canvas' style='height:500px; width: 800px'></div>
            </div>
        </td>
    </tr>
</table>
</td>
</tr>
